package zym.diandian.module.wifi;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import zym.diandian.R;
import zym.diandian.tools.ClipTool;
import zym.diandian.tools.NetUtil;

//WIFI密码查看
public class WifiFrame extends Fragment {

    private List<Wifi> wifiList = new ArrayList<>();
    private ListView listView;

    private int item_height = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            start();
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.wifi_fragment, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getActivity().setTitle("WIFI密码查看(长按可以复制密码)");

        this.listView = (ListView) view.findViewById(R.id.wifi_list);

        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            item_height = getResources().getDimensionPixelSize(x);
            Toast.makeText(getActivity(), "item_height:" + item_height, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        handler.sendEmptyMessageDelayed(0, 2000);

        this.listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Wifi item = wifiList.get(position);
                ClipTool.write(getActivity(), item.getPsd());

                Toast.makeText(getActivity(), "已复制(" + item.getPsd() + ")", Toast.LENGTH_SHORT).show();

                return false;
            }
        });

    }

    private void start() {
        DataOutputStream dos = null;
        InputStream inputStream = null;
        Process process = null;
        Runtime runtime = Runtime.getRuntime();

        try {
            process = runtime.exec("su");


            dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes("cd data/misc/wifi \n");
            dos.writeBytes("cat wpa_supplicant.conf \n");
            dos.writeBytes("exit \n");
            dos.flush();

            inputStream = process.getInputStream();
            String content = NetUtil.inputStream2String(inputStream);
            System.out.println("WIFI 密码 :" + content);

            Pattern pattern = Pattern.compile("\\{[^{\\}]*\\}");
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                System.out.println("group -------------" + matcher.group());
                String item = matcher.group();
                Wifi wifi = new Wifi();
                //ssid
                Matcher matcher_ssid = Pattern.compile("ssid=.*").matcher(item);
                if (matcher_ssid.find()) {
                    String ssid = matcher_ssid.group();
                    ssid = ssid.substring(5).replace("\"", "");
                    if (ssid.length() == 22 && ssid.startsWith("e")) {
                        //中文WIFI名字
                        Matcher matcher_name = Pattern.compile(".{2}").matcher(ssid);
                        ssid = "";
                        while (matcher_name.find()) {
                            ssid += "%" + matcher_name.group();
                        }
                    }
                    wifi.setSsid(URLDecoder.decode(ssid, "utf-8"));
                }
                //pwd
                Matcher matcher_pwd = Pattern.compile("psk=.*").matcher(item);
                if (matcher_pwd.find()) {
                    String pwd = matcher_pwd.group();
                    wifi.setPsd(pwd.substring(4).replace("\"", ""));
                }

                wifiList.add(wifi);

            }

            WIFIAdapter adapter = new WIFIAdapter(wifiList);
            listView.setAdapter(adapter);

            System.out.println("wifi name ++++++" + wifiList.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
    }

    private class WIFIAdapter extends BaseAdapter {
        private final AbsListView.LayoutParams lp;
        private List<Wifi> wifis;

        public WIFIAdapter(List<Wifi> wifiList) {
            this.wifis = wifiList;
            this.lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, item_height * 3);
        }

        @Override
        public int getCount() {
            return wifis.size();
        }

        @Override
        public Wifi getItem(int position) {
            return wifis.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.wifi_itme, null);
                holder = new ViewHolder();

                holder.ssid = (TextView) convertView.findViewById(R.id.wifi_ssid);
                holder.pwd = (TextView) convertView.findViewById(R.id.wifi_pwd);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.ssid.setText("SSID:" + getItem(position).getSsid());
            holder.pwd.setText("密码:" + getItem(position).getPsd());

            convertView.setLayoutParams(lp);

            return convertView;
        }
    }

    private class ViewHolder {
        TextView ssid;
        TextView pwd;
    }

}
